<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Admin\Controller;
use App\Models\LoginLogs;
use App\Models\User;
use App\Traits\Admin\SuccessOrFailure;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;

class LoginController extends Controller
{

    use SuccessOrFailure, Authorizable, Authorizable;

    protected $redirectTo = '/';

    public function __construct()
    {

        $this->middleware('guest', ['except' => 'logout']);
        $this->redirectTo = route('admin.index');

    }

    public function showLoginForm()
    {

//        if (Auth::check()) {
//            return $this->success('当前用户已经登录', route('admin.index'));
//        }
//        DB::table('users')->insert([
//            'name' => 'admin',
//            'mobile' => '15280400003',
//            'email' => 'admin@qq.com',
//            'password' => bcrypt('admin'),
////            'enable' => 1
//        ]);


        return view('admin.auth.login', ['captcha' => '']);
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'username' => 'required|string',
            'password' => 'required|string',
        ], [
            'username.required' => '请输入账号！',
            'username.string' => '请输入账号！',
            'password.required' => '请输入密码！',
            'password.string' => '请输入密码！',

        ]);

        $username = $request->input('username');
        if (is_mobile($username)) {
            $credentials['mobile'] = $username;
            $this->setLoginUserName('mobile');
        } else {
            $credentials['email'] = $username;
        }
        $credentials['password'] = $request->input('password');

        if (Auth::attempt($credentials)) {

            if (auth()->user()->enabled) {
                $request->session()->regenerate();
                /**
                 * 登录日志
                 */
                $loginLogs = new LoginLogs();
                $loginLogs->entry = 'admin';
                $loginLogs->user_id = Auth::id();
                $loginLogs->ip = $request->ip();
                $loginLogs->user_agent = $request->userAgent();
                $loginLogs->save();
                return $this->success('登录成功！', route('admin.index'));
            } else {
                Auth::logout();
                return $this->failure('账号已经禁用', route('guest.login'));
            }

        } else {
            return $this->failure('账号错误', route('guest.login'));
        }

    }


    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect(route('guest.login'));
    }
}
